import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

// 创建 axios 实例
const service = axios.create({
  baseURL: '/',
  timeout: 15000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    
    if (process.env.NODE_ENV === 'development') {
      console.log('Request URL:', config.url)
      console.log('Request Method:', config.method)
      console.log('Request Data:', config.data)
    }
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 如果是取消请求，不显示错误信息
    if (axios.isCancel(error)) {
      return Promise.reject(error)
    }

    if (error.response?.status === 404) {
      if (!error.config.url.includes('/logout')) {
        console.warn(`API not found: ${error.config.url}`)
      }
    } else {
      console.error('Request failed:', {
        url: error.config?.url,
        method: error.config?.method,
        status: error.response?.status,
        message: error.message
      })
    }

    if (error.response?.status === 401) {
      // 清除登录信息
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('redirectPath')
      router.push('/login')
    }

    if (!error.config.url.includes('/logout')) {
      // 根据错误类型显示不同的错误信息
      let errorMessage = '网络请求失败，请稍后重试'
      if (error.response?.data?.message) {
        errorMessage = error.response.data.message
      } else if (error.message.includes('timeout')) {
        errorMessage = '请求超时，请检查网络连接'
      } else if (error.message.includes('Network Error')) {
        errorMessage = '网络连接失败，请检查网络设置'
      }
      ElMessage.error(errorMessage)
    }
    return Promise.reject(error)
  }
)

export default service 